package com.hszl.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hszl.blog.dao.mapper.CategoryMapper;
import com.hszl.blog.dao.pojo.Category;
import com.hszl.blog.service.CategoryService;
import com.hszl.blog.vo.CategoryVo;
import com.hszl.blog.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 胡爽
 * @date: 2022/5/26 10:35
 **/
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public CategoryVo findCategoryById(Long id) {
        Category category = categoryMapper.selectById(id);
        CategoryVo categoryVo = new CategoryVo();
        BeanUtils.copyProperties(category,categoryVo);
        return categoryVo;
    }

    @Override
    public Result findAll() {
        List<Category> categoryList = categoryMapper.selectList(new QueryWrapper<>());
        return Result.success(copyList(categoryList));
    }

    @Override
    public Result findCategoryDetail() {
        List<Category> categories = categoryMapper.selectList(new QueryWrapper<>());
        return Result.success(copyList(categories));
    }

    @Override
    public Result findCategoryDetailById(Long id) {

        Category category = categoryMapper.selectById(id);
        return Result.success(copy(category));
    }

    private List<CategoryVo> copyList(List<Category> categoryList) {
        List<CategoryVo> categoryVoList = new ArrayList<>();

        for (Category category : categoryList) {
            categoryVoList.add(copy(category));
        }
        return categoryVoList;
    }

    private CategoryVo copy(Category category) {
        CategoryVo categoryVo = new CategoryVo();
        BeanUtils.copyProperties(category,categoryVo);
        categoryVo.setId(category.getId());
        categoryVo.setAvatar(category.getAvatar());
        categoryVo.setCategoryName(category.getCategoryName());
        return categoryVo;
    }
}
